package com.javasm.crm.controller.sell;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.javasm.crm.common.http.AxiosResult;
import com.javasm.crm.domin.criteria.SellOrderCriteria;
import com.javasm.crm.domin.criteria.SellOutRepositoryRecordCriteria;
import com.javasm.crm.domin.criteria.SellReturnOrderRecordCriteria;
import com.javasm.crm.domin.entity.sell.RepositorySellOutOrder;
import com.javasm.crm.domin.entity.sell.RepositorySellReturnOrder;
import com.javasm.crm.domin.entity.sell.SellOrder;
import com.javasm.crm.domin.entity.sell.SellOrderGoods;
import com.javasm.crm.domin.vo.SellOrderDetailVO;
import com.javasm.crm.domin.vo.SellOrderInfoVO;
import com.javasm.crm.domin.vo.SellOutRepositoryRecordVO;
import com.javasm.crm.domin.vo.SellReturnOrderRecordVO;

import com.javasm.crm.service.sell.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lqz
 * @since 2021-07-12
 */
@RestController
@RequestMapping("sellOrder")
public class SellOrderController {

    @Autowired
    ISellOrderService sellOrderService;

    @Autowired
    SellOrderInfoVOService sellOrderInfoVOService;

    @Autowired
    ISellOrderGoodsService sellOrderGoodsService;

    @Autowired
    SellOrderDetailVOService sellOrderDetailVOService;

    @Autowired
    IRepositorySellOutOrderService repositorySellOutOrderService;

    @Autowired
    SellOutRepositoryRecordVOService sellOutRepositoryRecordVOService;

    @Autowired
    IRepositorySellReturnOrderService repositorySellReturnOrderService;

    @Autowired
    SellReturnOrderRecordVOService sellReturnOrderRecordVOService;

    /**
     * 添加销售订单
     * @param sellOrderDetailVO
     * @return
     */
    public boolean addSellOrder(SellOrderDetailVO sellOrderDetailVO){
        return sellOrderService.addSellOrder(sellOrderDetailVO);
    }


    /**
     * 销售订单查询
     * @param sellOrderCriteria
     * @return 分页查询结果和响应码
     */
    @RequestMapping("searchByPage")
    public AxiosResult<Page<SellOrderInfoVO>> searchByPage(SellOrderCriteria sellOrderCriteria){
        Integer currentPage = sellOrderCriteria.getCurrentPage();
        Integer pageSize = sellOrderCriteria.getPageSize();
        if (null == currentPage && !"".equals(currentPage)){
            currentPage = 1;
        }
        if (null == pageSize && !"".equals(pageSize)){
            pageSize = 5;
        }
        LocalDateTime startTime = sellOrderCriteria.getStartTime();
        LocalDateTime endTime = sellOrderCriteria.getEndTime();
        String businessType = sellOrderCriteria.getBusinessType();
        String orderAction = sellOrderCriteria.getOrderAction();
        String orderState = sellOrderCriteria.getOrderState();
        String orderType = sellOrderCriteria.getOrderType();
        String payWay = sellOrderCriteria.getPayWay();
        String sellCode = sellOrderCriteria.getSellCode();

        QueryWrapper<SellOrderInfoVO> sellOrderInfoVOQueryWrapper = new QueryWrapper<>();
        LambdaQueryWrapper<SellOrderInfoVO> lambda = sellOrderInfoVOQueryWrapper.lambda();

        if (null != businessType && !"".equals(businessType)){
            lambda.eq(SellOrderInfoVO::getBusinessType,businessType);
        }
        if (null != orderAction && !"".equals(orderAction)){
            lambda.eq(SellOrderInfoVO::getOrderAction,orderAction);
        }
        if (null != orderState && !"".equals(orderState)){
            sellOrderInfoVOQueryWrapper.eq("s.order_state",orderState);
        }
        if (null != orderType && !"".equals(orderType)){
            lambda.eq(SellOrderInfoVO::getOrderType,orderType);
        }
        if (null != payWay && !"".equals(payWay)){
            lambda.eq(SellOrderInfoVO::getPayWay,payWay);
        }
        if (null != sellCode && !"".equals(sellCode)){
            sellOrderInfoVOQueryWrapper.like("o.sell_code",sellCode);
        }
        if (null != startTime && !"".equals(startTime) && null != endTime && !"".equals(endTime)){
            lambda.between(SellOrderInfoVO::getOrderCreateTime,startTime,endTime);
        }
        Page<SellOrderInfoVO> sellOrderInfoVOPage = new Page<>(currentPage,pageSize);
        List<SellOrderInfoVO> sellOrderInfoVOList = sellOrderInfoVOService.getSellOrderInfoVO(sellOrderInfoVOPage, sellOrderInfoVOQueryWrapper);
        sellOrderInfoVOPage.setRecords(sellOrderInfoVOList);
        return AxiosResult.success(sellOrderInfoVOPage);
    }

    @RequestMapping("searchDetail")
    public AxiosResult<SellOrderDetailVO> searchSellOrderDetail(String sellCode){
        //查找销售订单信息,连表查询
        SellOrderDetailVO sellOrderDetailVO = sellOrderDetailVOService.searchSellOrderDetailVO(sellCode);
        //查找销售订单商品列表
        QueryWrapper<SellOrderGoods> sellOrderGoodsQueryWrapper = new QueryWrapper<>();
        LambdaQueryWrapper<SellOrderGoods> goodsLambda = sellOrderGoodsQueryWrapper.lambda();
        if (null != sellCode && !"".equals(sellCode)){
            goodsLambda.eq(SellOrderGoods::getSellCode,sellCode);
        }
        List<SellOrderGoods> sellOrderGoodsList = sellOrderGoodsService.searchGoods(sellOrderGoodsQueryWrapper);
        sellOrderDetailVO.setSellOrderGoodsList(sellOrderGoodsList);
        return AxiosResult.success(sellOrderDetailVO);
    }

    @RequestMapping("addSellOutRepository")
    public AxiosResult<String> addSellOutRepository(@RequestBody ArrayList<String> sellCodeList){
        //遍历sellCodeList查询，添加到出库单数据
        if (null == sellCodeList || sellCodeList.isEmpty()){
            return AxiosResult.success("未选择订单");
        }
        //对sellCodeList中的值进行判断
        for (int i = 0; i < sellCodeList.size(); i++) {
            //在仓库中查找对应的订单
            QueryWrapper<RepositorySellOutOrder> wrapper = new QueryWrapper<>();
            LambdaQueryWrapper<RepositorySellOutOrder> lambda = wrapper.lambda();
            if (null != sellCodeList.get(i) && !"".equals(sellCodeList.get(i))){
                lambda.eq(RepositorySellOutOrder::getSellCode,sellCodeList.get(i));
            }
            RepositorySellOutOrder repositorySellOutOrder = repositorySellOutOrderService.searchOne(wrapper);
            if (repositorySellOutOrder != null){//订单在仓库中已存在，从list中删除
                sellCodeList.remove(i);
                i--;
            }
        }
        //再判断一次list是否为空
        if (sellCodeList.isEmpty()){
            return AxiosResult.success("订单已生成出库单");
        }
        //查找数据进行添加操作
        List<RepositorySellOutOrder> repositorySellOutOrderList = new ArrayList<>();
        for (String sellCode : sellCodeList) {
            QueryWrapper<SellOrder> sellOrderQueryWrapper = new QueryWrapper<>();
            LambdaQueryWrapper<SellOrder> goodsLambda = sellOrderQueryWrapper.lambda();
            if (null != sellCode && !"".equals(sellCode)){
                goodsLambda.eq(SellOrder::getSellCode,sellCode);
            }
            SellOrder sellOrder = sellOrderService.searchOne(sellOrderQueryWrapper);
            sellOrder.setOutOrderCreateTime(LocalDateTime.now());
            RepositorySellOutOrder repositorySellOutOrder = new RepositorySellOutOrder();
            mergeObject(sellOrder,repositorySellOutOrder);
            //存入销售出库数据库
            boolean b = repositorySellOutOrderList.add(repositorySellOutOrder);
            if(!b){
                AxiosResult.success("生成失败！");
            }
        }
        repositorySellOutOrderService.addAll(repositorySellOutOrderList);
        return AxiosResult.success("销售出库单生成成功！");
    }

    @RequestMapping("searchSellOutOrder")
    public AxiosResult<Page<SellOutRepositoryRecordVO>> searchSellOutOrder(@RequestBody SellOutRepositoryRecordCriteria sellOutRepositoryRecordCriteria){
        Integer currentPage = sellOutRepositoryRecordCriteria.getCurrentPage();
        Integer pageSize = sellOutRepositoryRecordCriteria.getPageSize();
        if (null == currentPage && !"".equals(currentPage)){
            currentPage = 1;
        }
        if (null == pageSize && !"".equals(pageSize)){
            pageSize = 5;
        }
        ArrayList<SellOutRepositoryRecordVO> list = new ArrayList<>();
        Page<SellOutRepositoryRecordVO>  sellOutRepositoryRecordVOPage = new Page<>(currentPage,pageSize);
        List<String> orderStateList = sellOutRepositoryRecordCriteria.getOrderStateList();
        for (String orderState : orderStateList) {

            LocalDateTime startTime = sellOutRepositoryRecordCriteria.getStartTime();
            LocalDateTime endTime = sellOutRepositoryRecordCriteria.getEndTime();
            String businessType = sellOutRepositoryRecordCriteria.getBusinessType();
            String orderAction = sellOutRepositoryRecordCriteria.getOrderAction();
            String orderType = sellOutRepositoryRecordCriteria.getOrderType();
            String payWay = sellOutRepositoryRecordCriteria.getPayWay();
            String sellCode = sellOutRepositoryRecordCriteria.getSellCode();

            QueryWrapper<SellOutRepositoryRecordVO> wrapper = new QueryWrapper<>();
            LambdaQueryWrapper<SellOutRepositoryRecordVO> lambda = wrapper.lambda();

            if (null != businessType && !"".equals(businessType)){
                lambda.eq(SellOutRepositoryRecordVO::getBusinessType,businessType);
            }
            if (null != orderAction && !"".equals(orderAction)){
                lambda.eq(SellOutRepositoryRecordVO::getOrderAction,orderAction);
            }
            if (null != orderState && !"".equals(orderState)){
                wrapper.eq("s.order_state",orderState);
            }
            if (null != orderType && !"".equals(orderType)){
                lambda.eq(SellOutRepositoryRecordVO::getOrderType,orderType);
            }
            if (null != payWay && !"".equals(payWay)){
                lambda.eq(SellOutRepositoryRecordVO::getPayWay,payWay);
            }
            if (null != sellCode && !"".equals(sellCode)){
                wrapper.like("o.sell_code",sellCode);
            }
            if (null != startTime && !"".equals(startTime) && null != endTime && !"".equals(endTime)){
                lambda.between(SellOutRepositoryRecordVO::getOutOrderCreateTime,startTime,endTime);
            }
            //替换TODO
            List<SellOutRepositoryRecordVO> sellOutRepositoryRecordVOList = sellOutRepositoryRecordVOService.getSellOutRepositoryRecordVO(sellOutRepositoryRecordVOPage, wrapper);
            list.addAll(sellOutRepositoryRecordVOList);
        }
        sellOutRepositoryRecordVOPage.setRecords(list);
        return AxiosResult.success(sellOutRepositoryRecordVOPage);
    }

    @RequestMapping("searchRecordDetail")
    public AxiosResult<List<SellOrderGoods>> searchRecordDetail(String sellCode){
        //查找销售订单商品列表
        QueryWrapper<SellOrderGoods> sellOrderGoodsQueryWrapper = new QueryWrapper<>();
        LambdaQueryWrapper<SellOrderGoods> goodsLambda = sellOrderGoodsQueryWrapper.lambda();
        if (null != sellCode && !"".equals(sellCode)){
            goodsLambda.eq(SellOrderGoods::getSellCode,sellCode);
        }
        List<SellOrderGoods> sellOrderGoodsList = sellOrderGoodsService.searchGoods(sellOrderGoodsQueryWrapper);
        return AxiosResult.success(sellOrderGoodsList);
    }

    @RequestMapping("addSellReturnOrder")
    public AxiosResult<String> addSellReturnOrder(@RequestBody RepositorySellReturnOrder repositorySellReturnOrder){
        //先查找，如果存在，返回已存在
        QueryWrapper<RepositorySellReturnOrder> wrapper = new QueryWrapper<>();
        LambdaQueryWrapper<RepositorySellReturnOrder> lambda = wrapper.lambda();
        if (null != repositorySellReturnOrder.getSellCode() && !"".equals(repositorySellReturnOrder.getSellCode())){
            lambda.eq(RepositorySellReturnOrder::getSellCode,repositorySellReturnOrder.getSellCode());
        }
        //查找
        RepositorySellReturnOrder sellReturnOrder = repositorySellReturnOrderService.searchOne(wrapper);
        if (sellReturnOrder != null){
            return AxiosResult.success("此退货单已创建");
        }
        boolean b = repositorySellReturnOrderService.addOne(repositorySellReturnOrder);
        if (!b){
            return AxiosResult.success("创建失败！");
        }
        return AxiosResult.success("创建成功！");
    }

    @RequestMapping("searchSellReturnOrder")
    public AxiosResult<Page<SellReturnOrderRecordVO>> searchSellReturnOrder(@RequestBody SellReturnOrderRecordCriteria sellReturnOrderRecordCriteria){
        //先取出所有数据
        Integer currentPage = sellReturnOrderRecordCriteria.getCurrentPage();
        Integer pageSize = sellReturnOrderRecordCriteria.getPageSize();
        if (null == currentPage && !"".equals(currentPage)){
            currentPage = 1;
        }
        if (null == pageSize && !"".equals(pageSize)){
            pageSize = 5;
        }
        LocalDateTime startTime = sellReturnOrderRecordCriteria.getStartTime();
        LocalDateTime endTime = sellReturnOrderRecordCriteria.getEndTime();
        String sellCode = sellReturnOrderRecordCriteria.getSellCode();
        String consigneeName = sellReturnOrderRecordCriteria.getConsigneeName();
        String refuseReason = sellReturnOrderRecordCriteria.getRefuseReason();
        String deliveryAddress = sellReturnOrderRecordCriteria.getDeliveryAddress();
        Page<SellReturnOrderRecordVO> page = new Page<>();
        QueryWrapper<SellReturnOrderRecordVO> wrapper = new QueryWrapper<>();
        LambdaQueryWrapper<SellReturnOrderRecordVO> lambda = wrapper.lambda();
        if (null != refuseReason && !"".equals(refuseReason)){
            wrapper.eq("r.refuse_reason",refuseReason);
        }
        if (null != sellCode && !"".equals(sellCode)){
            wrapper.like("r.sell_code",sellCode);
        }
        if (null != consigneeName && !"".equals(consigneeName)){
            wrapper.like("r.consignee_name",consigneeName);
        }
        if (null != deliveryAddress && !"".equals(deliveryAddress)){
            wrapper.like("r.delivery_address",deliveryAddress);
        }
        if (null != startTime && !"".equals(startTime) && null != endTime && !"".equals(endTime)){
            lambda.between(SellReturnOrderRecordVO::getSellReturnCreateTime,startTime,endTime);
        }
        List<SellReturnOrderRecordVO> sellReturnOrderRecordVOList = sellReturnOrderRecordVOService.getSellReturnOrderRecordVO(page, wrapper);
        page.setRecords(sellReturnOrderRecordVOList);
        return AxiosResult.success(page);
    }

    /**
     * 将sellOrder对象的属性值赋值给repositorySellOutOrder对象的同名属性
     * @param origin
     * @param destination
     */
    public void mergeObject(SellOrder origin, RepositorySellOutOrder destination) {
        if (origin == null || destination == null)
            return;
        Field[] fields = origin.getClass().getDeclaredFields();
        Field[] desFields = destination.getClass().getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            try {
                fields[i].setAccessible(true);
                Object value = fields[i].get(origin);
                String name = fields[i].getName();
                for (int j = 0; j < desFields.length; j++) {
                    desFields[j].setAccessible(true);
                    String desName = desFields[j].getName();
                    if (desName.equals(name) && null != value){
                        desFields[j].set(destination,value);
                    }
                    desFields[j].setAccessible(false);
                }
                fields[i].setAccessible(false);
            } catch (Exception e) {
            }
        }
    }
}
